package com.etone.smartAudit.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.etone.smartAudit.domain.Dictionary;
import com.etone.smartAudit.dto.admin.SimpleAdminDTO;
import com.etone.smartAudit.dto.dictionary.DictionaryDTO;
import com.etone.smartAudit.mapper.DictionaryMapper;
import com.etone.smartAudit.vo.dictionary.DictionaryVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author: sovy
 * @date: 2020/8/4
 * @description:
 */
@Service
@AllArgsConstructor
public class DictionaryService {
    private DictionaryMapper dictionaryMapper;

    /**
     * 查询单个键
     *
     * @param code
     * @return
     */
    public Dictionary findByCode(String code) {
        return dictionaryMapper.findByCode(code);
    }

    public String findValueByCode(String code) {
        Dictionary dictionary = findByCode(code);
        return dictionary == null ? null : dictionary.getValue();
    }

    /**
     * 查询多个键
     *
     * @param codes
     * @return
     */
    public List<DictionaryVO> findByCode(List<String> codes) {
        return dictionaryMapper.findByCodes(codes);
    }

    /**
     * 修改字典
     *
     * @param dictionaryDTOS
     * @return
     */
    public void update(List<DictionaryDTO> dictionaryDTOS) {
        if (!CollectionUtils.isEmpty(dictionaryDTOS)) {
            dictionaryDTOS.forEach(dictionaryDTO -> {
                dictionaryMapper.updateByCode(dictionaryDTO.getCode(), dictionaryDTO.getValue());
            });

        }
    }

    /**
     * 获取审核人员
     *
     * @param code
     * @return
     */
    public SimpleAdminDTO getCheckingMember(String code) {
        String value = findValueByCode(code);
        JSONArray jsonArray = JSONArray.parseArray(value);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        Integer nodeAdminId = jsonObject.getInteger("id");
        String nodeAdminName = jsonObject.getString("name");
        return SimpleAdminDTO.builder().id(nodeAdminId).nickName(nodeAdminName).build();
    }
}
